package com.dal.consumer.service;

import com.dal.message.UserInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQReplyListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
@RocketMQMessageListener(topic = "users", consumerGroup = "${demo.rocketmq.consumer.group}",selectorExpression = "userReg")
public class UsersMQMessageListener    implements
        RocketMQReplyListener<UserInfo,String>
//        RocketMQPushConsumerLifecycleListener
{
    @Resource
    ObjectMapper mapper;
    @Resource
    RedisTemplate<String,Object> redisTemplate;

    @Override
    public String onMessage(UserInfo userInfo) {
//        获取消息，并在控制台打印（生产者一有消息就接收了）
        log.info("UsersMQ onMessage 接收信息："+userInfo);
        //            var userInfo=mapper.readValue(s, UserInfo.class);
        var userKey="users_"+userInfo.getName();
        UserInfo user = (UserInfo) redisTemplate.opsForValue().get(userKey);
        if (user!=null){
            return "用户已经存在";
        }
        redisTemplate.opsForValue().set("users_"+userInfo.getName(), userInfo);


        return "注册成功";
    }

}
